<html>
<head>
  <title>HttpClient.class.php</title>
</head>
<body bgcolor="#ffffff" text="#000000">
<pre>
&lt;?php

/* Version 0.9, 6th April 2003 - Simon Willison ( http://simon.incutio.com/ )
   Manual: http://scripts.incutio.com/httpclient/
*/

class HttpClient {
    // Request vars
    var $host;
    var $port;
    var $path;
    var $method;
    var $postdata = '';
    var $cookies = array();
    var $referer;
    var $accept = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*';
    var $accept_encoding = 'gzip';
    var $accept_language = 'en-us';
    var $user_agent = 'Incutio HttpClient v0.9';
    // Options
    var $timeout = 20;
    var $use_gzip = true;
    var $persist_cookies = true;  // If true, received cookies are placed in the $this-&gt;cookies array ready for the next request
                                  // Note: This currently ignores the cookie path (and time) completely. Time is not important, 
                                  //       but path could possibly lead to security problems.
    var $persist_referers = true; // For each request, sends path of last request as referer
    var $debug = false;
    var $handle_redirects = true; // Auaomtically redirect if Location or URI header is found
    var $max_redirects = 5;
    var $headers_only = false;    // If true, stops receiving once headers have been read.
    // Basic authorization variables
    var $username;
    var $password;
    // Response vars
    var $status;
    var $headers = array();
    var $content = '';
    var $errormsg;
    // Tracker variables
    var $redirect_count = 0;
    var $cookie_host = '';
    function HttpClient($host, $port=80) {
        $this-&gt;host = $host;
        $this-&gt;port = $port;
    }
    function get($path, $data = false) {
        $this-&gt;path = $path;
        $this-&gt;method = 'GET';
        if ($data) {
            $this-&gt;path .= '?'.$this-&gt;buildQueryString($data);
        }
        return $this-&gt;doRequest();
    }
    function post($path, $data) {
        $this-&gt;path = $path;
        $this-&gt;method = 'POST';
        $this-&gt;postdata = $this-&gt;buildQueryString($data);
    	return $this-&gt;doRequest();
    }
    function buildQueryString($data) {
        $querystring = '';
        if (is_array($data)) {
            // Change data in to postable data
    		foreach ($data as $key =&gt; $val) {
    			if (is_array($val)) {
    				foreach ($val as $val2) {
    					$querystring .= urlencode($key).'='.urlencode($val2).'&amp;';
    				}
    			} else {
    				$querystring .= urlencode($key).'='.urlencode($val).'&amp;';
    			}
    		}
    		$querystring = substr($querystring, 0, -1); // Eliminate unnecessary &amp;
    	} else {
    	    $querystring = $data;
    	}
    	return $querystring;
    }
    function doRequest() {
        // Performs the actual HTTP request, returning true or false depending on outcome
		if (!$fp = @fsockopen($this-&gt;host, $this-&gt;port, $errno, $errstr, $this-&gt;timeout)) {
		    // Set error message
            switch($errno) {
				case -3:
					$this-&gt;errormsg = 'Socket creation failed (-3)';
				case -4:
					$this-&gt;errormsg = 'DNS lookup failure (-4)';
				case -5:
					$this-&gt;errormsg = 'Connection refused or timed out (-5)';
				default:
					$this-&gt;errormsg = 'Connection failed ('.$errno.')';
			    $this-&gt;errormsg .= ' '.$errstr;
			    $this-&gt;debug($this-&gt;errormsg);
			}
			return false;
        }
        socket_set_timeout($fp, $this-&gt;timeout);
        $request = $this-&gt;buildRequest();
        $this-&gt;debug('Request', $request);
        fwrite($fp, $request);
    	// Reset all the variables that should not persist between requests
    	$this-&gt;headers = array();
    	$this-&gt;content = '';
    	$this-&gt;errormsg = '';
    	// Set a couple of flags
    	$inHeaders = true;
    	$atStart = true;
    	// Now start reading back the response
    	while (!feof($fp)) {
    	    $line = fgets($fp, 4096);
    	    if ($atStart) {
    	        // Deal with first line of returned data
    	        $atStart = false;
    	        if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) {
    	            $this-&gt;errormsg = &quot;Status code line invalid: &quot;.htmlentities($line);
    	            $this-&gt;debug($this-&gt;errormsg);
    	            return false;
    	        }
    	        $http_version = $m[1]; // not used
    	        $this-&gt;status = $m[2];
    	        $status_string = $m[3]; // not used
    	        $this-&gt;debug(trim($line));
    	        continue;
    	    }
    	    if ($inHeaders) {
    	        if (trim($line) == '') {
    	            $inHeaders = false;
    	            $this-&gt;debug('Received Headers', $this-&gt;headers);
    	            if ($this-&gt;headers_only) {
    	                break; // Skip the rest of the input
    	            }
    	            continue;
    	        }
    	        if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) {
    	            // Skip to the next header
    	            continue;
    	        }
    	        $key = strtolower(trim($m[1]));
    	        $val = trim($m[2]);
    	        // Deal with the possibility of multiple headers of same name
    	        if (isset($this-&gt;headers[$key])) {
    	            if (is_array($this-&gt;headers[$key])) {
    	                $this-&gt;headers[$key][] = $val;
    	            } else {
    	                $this-&gt;headers[$key] = array($this-&gt;headers[$key], $val);
    	            }
    	        } else {
    	            $this-&gt;headers[$key] = $val;
    	        }
    	        continue;
    	    }
    	    // We're not in the headers, so append the line to the contents
    	    $this-&gt;content .= $line;
        }
        fclose($fp);
        // If data is compressed, uncompress it
        if (isset($this-&gt;headers['content-encoding']) &amp;&amp; $this-&gt;headers['content-encoding'] == 'gzip') {
            $this-&gt;debug('Content is gzip encoded, unzipping it');
            $this-&gt;content = substr($this-&gt;content, 10); // See http://www.php.net/manual/en/function.gzencode.php
            $this-&gt;content = gzinflate($this-&gt;content);
        }
        // If $persist_cookies, deal with any cookies
        if ($this-&gt;persist_cookies &amp;&amp; isset($this-&gt;headers['set-cookie']) &amp;&amp; $this-&gt;host == $this-&gt;cookie_host) {
            $cookies = $this-&gt;headers['set-cookie'];
            if (!is_array($cookies)) {
                $cookies = array($cookies);
            }
            foreach ($cookies as $cookie) {
                if (preg_match('/([^=]+)=([^;]+);/', $cookie, $m)) {
                    $this-&gt;cookies[$m[1]] = $m[2];
                }
            }
            // Record domain of cookies for security reasons
            $this-&gt;cookie_host = $this-&gt;host;
        }
        // If $persist_referers, set the referer ready for the next request
        if ($this-&gt;persist_referers) {
            $this-&gt;debug('Persisting referer: '.$this-&gt;getRequestURL());
            $this-&gt;referer = $this-&gt;getRequestURL();
        }
        // Finally, if handle_redirects and a redirect is sent, do that
        if ($this-&gt;handle_redirects) {
            if (++$this-&gt;redirect_count &gt;= $this-&gt;max_redirects) {
                $this-&gt;errormsg = 'Number of redirects exceeded maximum ('.$this-&gt;max_redirects.')';
                $this-&gt;debug($this-&gt;errormsg);
                $this-&gt;redirect_count = 0;
                return false;
            }
            $location = isset($this-&gt;headers['location']) ? $this-&gt;headers['location'] : '';
            $uri = isset($this-&gt;headers['uri']) ? $this-&gt;headers['uri'] : '';
            if ($location || $uri) {
                $url = parse_url($location.$uri);
                // This will FAIL if redirect is to a different site
                return $this-&gt;get($url['path']);
            }
        }
        return true;
    }
    function buildRequest() {
        $headers = array();
        $headers[] = &quot;{$this-&gt;method} {$this-&gt;path} HTTP/1.0&quot;; // Using 1.1 leads to all manner of problems, such as &quot;chunked&quot; encoding
        $headers[] = &quot;Host: {$this-&gt;host}&quot;;
        $headers[] = &quot;User-Agent: {$this-&gt;user_agent}&quot;;
        $headers[] = &quot;Accept: {$this-&gt;accept}&quot;;
        if ($this-&gt;use_gzip) {
            $headers[] = &quot;Accept-encoding: {$this-&gt;accept_encoding}&quot;;
        }
        $headers[] = &quot;Accept-language: {$this-&gt;accept_language}&quot;;
        if ($this-&gt;referer) {
            $headers[] = &quot;Referer: {$this-&gt;referer}&quot;;
        }
    	// Cookies
    	if ($this-&gt;cookies) {
    	    $cookie = 'Cookie: ';
    	    foreach ($this-&gt;cookies as $key =&gt; $value) {
    	        $cookie .= &quot;$key=$value; &quot;;
    	    }
    	    $headers[] = $cookie;
    	}
    	// Basic authentication
    	if ($this-&gt;username &amp;&amp; $this-&gt;password) {
    	    $headers[] = 'Authorization: BASIC '.base64_encode($this-&gt;username.':'.$this-&gt;password);
    	}
    	// If this is a POST, set the content type and length
    	if ($this-&gt;postdata) {
    	    $headers[] = 'Content-Type: application/x-www-form-urlencoded';
    	    $headers[] = 'Content-Length: '.strlen($this-&gt;postdata);
    	}
    	$request = implode(&quot;\r\n&quot;, $headers).&quot;\r\n\r\n&quot;.$this-&gt;postdata;
    	return $request;
    }
    function getStatus() {
        return $this-&gt;status;
    }
    function getContent() {
        return $this-&gt;content;
    }
    function getHeaders() {
        return $this-&gt;headers;
    }
    function getHeader($header) {
        $header = strtolower($header);
        if (isset($this-&gt;headers[$header])) {
            return $this-&gt;headers[$header];
        } else {
            return false;
        }
    }
    function getError() {
        return $this-&gt;errormsg;
    }
    function getCookies() {
        return $this-&gt;cookies;
    }
    function getRequestURL() {
        $url = 'http://'.$this-&gt;host;
        if ($this-&gt;port != 80) {
            $url .= ':'.$this-&gt;port;
        }            
        $url .= $this-&gt;path;
        return $url;
    }
    // Setter methods
    function setUserAgent($string) {
        $this-&gt;user_agent = $string;
    }
    function setAuthorization($username, $password) {
        $this-&gt;username = $username;
        $this-&gt;password = $password;
    }
    function setCookies($array) {
        $this-&gt;cookies = $array;
    }
    // Option setting methods
    function useGzip($boolean) {
        $this-&gt;use_gzip = $boolean;
    }
    function setPersistCookies($boolean) {
        $this-&gt;persist_cookies = $boolean;
    }
    function setPersistReferers($boolean) {
        $this-&gt;persist_referers = $boolean;
    }
    function setHandleRedirects($boolean) {
        $this-&gt;handle_redirects = $boolean;
    }
    function setMaxRedirects($num) {
        $this-&gt;max_redirects = $num;
    }
    function setHeadersOnly($boolean) {
        $this-&gt;headers_only = $boolean;
    }
    function setDebug($boolean) {
        $this-&gt;debug = $boolean;
    }
    // &quot;Quick&quot; static methods
    function quickGet($url) {
        $bits = parse_url($url);
        $host = $bits['host'];
        $port = isset($bits['port']) ? $bits['port'] : 80;
        $path = isset($bits['path']) ? $bits['path'] : '/';
        if (isset($bits['query'])) {
            $path .= '?'.$bits['query'];
        }
        $client = new HttpClient($host, $port);
        if (!$client-&gt;get($path)) {
            return false;
        } else {
            return $client-&gt;getContent();
        }
    }
    function quickPost($url, $data) {
        $bits = parse_url($url);
        $host = $bits['host'];
        $port = isset($bits['port']) ? $bits['port'] : 80;
        $path = isset($bits['path']) ? $bits['path'] : '/';
        $client = new HttpClient($host, $port);
        if (!$client-&gt;post($path, $data)) {
            return false;
        } else {
            return $client-&gt;getContent();
        }
    }
    function debug($msg, $object = false) {
        if ($this-&gt;debug) {
            print '&lt;div style=&quot;border: 1px solid red; padding: 0.5em; margin: 0.5em;&quot;&gt;&lt;strong&gt;HttpClient Debug:&lt;/strong&gt; '.$msg;
            if ($object) {
                ob_start();
        	    print_r($object);
        	    $content = htmlentities(ob_get_contents());
        	    ob_end_clean();
        	    print '&lt;pre&gt;'.$content.'&lt;/pre&gt;';
        	}
        	print '&lt;/div&gt;';
        }
    }   
}

?&gt;
</pre>
<hr>
syntax highlighted by <a href="http://www.palfrader.org/code2html">Code2HTML</a>, v. 0.9.1
</body>
</html>
